<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>关联OTA产品配置</title>
    <script src="__PUBLIC__/jquery/jquery.min.js"></script>
    <link rel="stylesheet" href="__PUBLIC__/layui/css/layui.css"  media="all">
    <link rel="stylesheet" href="__PUBLIC__/font-awesome/css/font-awesome.min.css" media="all" />
    <link rel="stylesheet" href="__CSS__/admin.css"  media="all">
</head>
<style>
    .site-content{
        padding: 20px 0 10px 20px;
    }
    .table_input{
        width: 80px;
        display: inline-block;
        margin: 0 10px;
    }

    .must_input_star{
        font-size: 16px !important;
        color:red;
        margin-right: 2px;
    }
    .uploadimgbox{
        margin: 4px 10px;
    }
    .uploadimgbox img{
        height: 60px;
        padding: 4px;
    }

    .list-group-item{
        margin: 5px 30px 5px 0;
        color: #212529;
        display: inline-block;
    }
    .list-group-item>i,.uploadimgbox>i{
        color:red;
    }
    .example2 .list-group-item{
        background: #d2d2d2;
        padding: 2px 10px;
    }
    .bcStartDate,.startComboDate,.endComboDate{
        width: 40%;
    }
</style>
<body>
<div class="site-inline">
    <div class="site-content">
        <form class="layui-form " id="otaConfigForm">
            <input name="product_id" id="product_id" type="hidden" value="{$ota_config.product_id}">
            <div class="layui-form-item">
                <label class="layui-form-label"><span class="must_input_star">*</span>主图：</label>
                <div class="layui-input-block">
                    <div class="layui-upload">
                        <button type="button" class="layui-btn" id="proImages"><i class="layui-icon"></i>{:lang('上传')}（{:lang('格式')}：jpg,png,gif,jpeg）                                                                                      </button>
                        <span class="must_input_star">*</span>
                        <span style="color:#999;font-size: 14px;">{:lang('产品主图，至少1张，至多5张，尺寸不小于800*800')}</span>
                        <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                            {:lang('预览')}：
                            <div class="layui-upload-list example3" id="proImageList">

                            </div>
                        </blockquote>
                    </div>
                    <input type="hidden" name="ota_images" value="" >

                </div>
            </div>

            <div class="layui-form-item ">
                <div class="layui-inline">
                    <label class="layui-form-label">商品类型</label>
                    <div class="layui-input-block">
                        <select name="item_type" id="item_type" lay-verify="required" lay-filter="selectItemType">
                            <option value="">请选择商品类型</option>
                            {notempty name="$itemTypes"}{volist name="itemTypes" id="vo"}
                            <option value="{$vo}" {if $ota_config.item_type==$vo}selected{/if}>{$vo}</option>
                            {/volist}{/notempty}
                        </select>
                    </div>
                </div>
            </div>

            <div class="layui-form-item ">
                <div class="layui-inline">
                    <label class="layui-form-label">售卖类型</label>
                    <div class="layui-input-block">
                        <input type="radio" name="sale_type" lay-filter="changeSaleType" value="0" title="日历商品" {empty name="$ota_config.sale_type"}checked{/empty}>
                        <input type="radio" name="sale_type" lay-filter="changeSaleType" value="1" title="预约商品" {notempty name="$ota_config.sale_type"}{if $ota_config.sale_type==1}checked{/if}{/notempty}>
                        <input type="radio" name="sale_type" lay-filter="changeSaleType" value="2" title="非日历商品" {notempty name="$ota_config.sale_type"}{if $ota_config.sale_type==2}checked{/if}{/notempty}>
                        <span class="layui-inline" style="padding-top: 10px;color:#c9c9c9;">提示：选择预约商品，预约商品开始时间和可选出发开始结束时间则必填</span>
                        <!--<span class="layui-inline showSaleType" style="padding-top: 10px;"><i class="layui-icon">&#xe60b;</i></span>-->
                    </div>
                </div>
            </div>

            <div class="layui-form-item bcStartDate">
                <label class="layui-form-label">预约商品<br>开始时间</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input bc_start_date" value="{notempty name='$ota_config.bc_start_date'}{$ota_config.bc_start_date|date='Y-m-d H:i:s',###}{/notempty}" name="bc_start_date">
                </div>
            </div>

            <div class="layui-form-item startComboDate">
                <label class="layui-form-label">可选出发<br>开始时间</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input start_combo_date" value="{notempty name='$ota_config.start_combo_date'}{$ota_config.start_combo_date|date='Y-m-d H:i:s',###}{/notempty}" name="start_combo_date">
                </div>
            </div>

            <div class="layui-form-item endComboDate">
                <label class="layui-form-label">可选出发<br>结束时间</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input end_combo_date" value="{notempty name='$ota_config.end_combo_date'}{$ota_config.end_combo_date|date='Y-m-d H:i:s',###}{/notempty}" name="end_combo_date">
                </div>
            </div>

            <div class="layui-form-item ">
                <label class="layui-form-label">提供发票</label>
                <div class="layui-input-block">
                    <input type="radio" name="has_invoice" value="1" title="是" {notempty name="$ota_config.has_invoice"}{if $ota_config.has_invoice==1}checked{/if}{/notempty}>
                    <input type="radio" name="has_invoice" value="0" title="否" {empty name="$ota_config.has_invoice"}checked{/empty}>
                </div>
            </div>

            <div class="layui-form-item ">
                <label class="layui-form-label">支持打折</label>
                <div class="layui-input-block">
                    <input type="radio" name="has_discount" value="1" title="是" {notempty name="$ota_config.has_discount"}{if $ota_config.has_discount==1}checked{/if}{/notempty}>
                    <input type="radio" name="has_discount" value="0" title="否" {empty name="$ota_config.has_discount"}checked{/empty}>
                </div>
            </div>

            <div class="layui-form-item ">
                <label class="layui-form-label">橱窗展示</label>
                <div class="layui-input-block">
                    <input type="radio" name="has_showcase" value="1" title="是" {notempty name="$ota_config.has_showcase"}{if $ota_config.has_showcase==1}checked{/if}{/notempty}>
                    <input type="radio" name="has_showcase" value="0" title="否" {empty name="$ota_config.has_showcase"}checked{/empty}>
                </div>
            </div>

            {if $product.service_type==2}
            <div class="layui-form-item ">
                <label class="layui-form-label">门票设置</label>
                <div class="layui-input-block">
                    <a class="layui-btn layui-btn-warm layui-btn-sm otaTicketConfig">点击跳转到门票配置</a>
                    <span class="layui-inline" style="padding-top: 10px;color:#c9c9c9;">提示：跳转到门票配置页面。</span>

                </div>
            </div>
            {/if}
            <div class="layui-form-item ">
                <div class="layui-inline">
                    <label class="layui-form-label">取消政策</label>
                    <div class="layui-input-block">
                        <a class="layui-btn layui-btn-sm addCancelRule">增加规则</a>

                        <table class="layui-table" lay-skin="" lay-size="sm">
                            <tr>
                                <th>出行前</th>
                                <th>买家违约</th>
                                <th>卖家违约</th>
                                <th>操作</th>
                            </tr>
                            <tbody class="table_body">

                            </tbody>
                        </table>
                    </div>
                </div>
            </div>

            <div class="layui-form-item ">
                <div class="layui-inline">
                    <label class="layui-form-label"></label>
                    <div class="layui-input-block">
                        <button lay-submit="" class="layui-btn layui-btn-bg layui-btn-normal submitForm">提交</button>
                    </div>
                </div>
            </div>
        </form>

    </div>
</div>
</body>

<script src="__PUBLIC__/layui/layui.js"></script>
<script src="__PUBLIC__/jquery/jquery.min.js"></script>
<script>
    layui.config({
        base : '__PUBLIC__/'
    }).extend({
        selectM: './multiple/selectM'
    }).use(['layer','form','jquery','selectM','upload','laydate'],function(){
        var layer = layui.layer,
            $ = layui.jquery,
            form = layui.form,
            laydate = layui.laydate,
            upload = layui.upload,
            selectM = layui.selectM;
        const max_goods_image_num = 5;
        laydate.render({     //创建时间选择框
            elem: '.bc_start_date' //指定元素
            ,format: 'yyyy-MM-dd HH:mm:ss'
            ,trigger:'click'
            ,type:'datetime'
        });
        laydate.render({     //创建时间选择框
            elem: '.start_combo_date' //指定元素
            ,format: 'yyyy-MM-dd HH:mm:ss'
            ,trigger:'click'
            ,type:'datetime'

        });
        laydate.render({     //创建时间选择框
            elem: '.end_combo_date' //指定元素
            ,format: 'yyyy-MM-dd HH:mm:ss'
            ,trigger:'click'
            ,type:'datetime'

        });

        //图片和视频上传
        upload.render({
            elem: '#proImages'
            ,url: "{:url('common/uploadImgLimit800')}"
            ,multiple: true
            ,accept:"images"
            ,size:"50000"
            ,done: function(res){
                //上传完毕回调
                layer.closeAll('loading');
                if(res.code != 2){ layer.msg(res.msg);return false;}
                if($('#proImageList').find('img').length >= max_goods_image_num){
                    layer.msg('最多只能上传'+max_goods_image_num+'张！');return false;
                }

                $('#proImageList').append('<span class="uploadimgbox"><img class="layui-upload-img" src="'+res.src+'"><i class="layui-icon">&#x1006;</i></span>');
                var goods_images = $('input[name=ota_images]').val();
                if(goods_images!='' && goods_images!=undefined){
                    goods_images = goods_images.split(',');
                    goods_images.push(res.src);
                    goods_images = goods_images.join(',');
                }else{
                    goods_images = res.src;
                }
                $('input[name=ota_images]').val(goods_images);

                return false;
            }
            ,error: function(){
                //请求异常回调
                //演示失败状态，并实现重传
                layer.closeAll('loading');
                layer.msg('上传失败');
                return false;
            }
            ,before:function () {
                layer.load(2);
            }
        });
        //绑定删除图片
        $("#proImageList").on('click','.layui-icon',function () {
            $(this).parent().remove();
            renderImagesValue("#proImageList","ota_images");
        })

        var cancelRules = {$ota_config.cancel_rules|json_encode}

        //渲染取消政策数据
        function renderCancelRuleHtml(cancelRules)
        {
            if(cancelRules.length < 1) return false;
            $('.table_body').children().remove();
            $.each(cancelRules,function (i,v) {
                var rule = v.split('_');
                var title = getCancelRuleTitle(rule[0],rule[1]);
                var buyer_td_html = getCancelRuleBuyerTitle(rule[2]);
                var seller_td_html = getCancelRuleSellerTitle(rule[3]);
                var operate_td_html = getCancelRuleOperateTitle(rule[0],rule[1],i);
                var tr_html = '<tr data-index="'+i+'">' +
                    '<td>'+title+'</td>' +
                    '<td>'+buyer_td_html+'</td>' +
                    '<td>'+seller_td_html+'</td>' +
                    '<td>'+operate_td_html+'</td>' +
                    '</tr>';
                $('.table_body').append(tr_html);
            });
            //渲染input
            form.render();
        }

        function getCancelRuleTitle(start,end)
        {
            var html_input_start = '<input value="'+ start +'" type="number" lay-verify="required" class="layui-input table_input startDay" data-index="0">';
            var html_input_end = '<input value="'+ end +'" type="number" lay-verify="required" class="layui-input table_input endDay" data-index="1">';
            return start==end && start=='0' ? '出发当日':
                (start=='-1' && end > 0 ? html_input_end + '日及以上' : html_input_end + '日至' + html_input_start + '日');
        }

        function getCancelRuleBuyerTitle(buyer_percent){
            return '<span>收取总费用的</span><input value="' +buyer_percent+ '" type="number" lay-verify="required" class="layui-input table_input buyerPercent" data-index="2">%的费用';
        }
        function getCancelRuleSellerTitle(seller_percent){
            return '<span>支付总费用的</span><input value="' +seller_percent+ '" type="number" lay-verify="required" class="layui-input table_input sellerPercent" data-index="3">%的费用';
        }
        function getCancelRuleOperateTitle(start='',end='',index=''){
            if($.inArray(start,['0','-1']) > -1) return '';
            return '<a class="delCancelRule" data-index="' +index+ '" style="color:#00c0ef">删除</a>';
        }

        $('.addCancelRule').click(function () {
            //最多五条规则
            if(cancelRules.length >=5){layer.msg('最多支持5条规则');return false;}
            var last_rule = cancelRules[cancelRules.length -1];
            cancelRules[cancelRules.length -1] = '__0_0_0';
            cancelRules.push(last_rule);
            console.log(cancelRules)
            //初始化取消政策
            renderCancelRuleHtml(cancelRules);
        })
        $('table').on('click','.delCancelRule',function () {
            var index = $(this).attr('data-index');
            delete cancelRules[index];
            cancelRules = cancelRules.filter(function (s) {
                return s && s.trim();
            });
            console.log(cancelRules);
            //删除节点
            $(this).parent().parent().remove();
        })

        $('table').on('blur','.startDay,.endDay,.buyerPercent,.sellerPercent',function () {
            if($(this).val()=='' || $(this).val()==null){return false;}
            var rule_index = $(this).attr('data-index');
            var cancel_rules_index = $(this).parent().parent().attr('data-index');
            var rule = cancelRules[cancel_rules_index];
            var rule = rule.split('_');
            rule[rule_index] = $(this).val();
            if(cancel_rules_index==='0' && rule_index==='0'){
                rule[1] = $(this).val();
            }else if(cancel_rules_index > 0 && $.inArray(rule_index,['1','0']) > -1){
                if(parseInt(rule[0]) < parseInt(rule[1])){
                    var temp = rule[0];rule[0] = rule[1];rule[1] = temp;
                }
            }
            cancelRules[cancel_rules_index] = rule.join('_');

        })

        function checkCancelRules()
        {
            console.log(cancelRules);
            var flag = true;
            $.each(cancelRules,function (i,v) {
                var rule = v.split('_');
                if(rule[0]=='' || rule[1]=='' || rule[2]=='' || rule[4]==''){
                    flag = false;
                    layer.msg('请补充所有的规则数据！');return false;
                }
            })
            return flag;
        }

        function checkSaleType()
        {
            //预约商品 检测时间是否填写
            if($('input[name=sale_type]:checked').val()==1){
                if($('input[name=bc_start_date]').val()==''){layer.msg('请选择预约商品开始时间！');return false;}
                if($('input[name=start_combo_date]').val()==''){layer.msg('请选择可选出发开始时间！');return false;}
                if($('input[name=end_combo_date]').val()==''){layer.msg('请选择可选出发结束时间！');return false;}
            }
            return true;
        }

        /**
         * 自动将form表单封装成json对象
         */
        $.fn.serializeObject = function() {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) {
                        o[this.name] = [ o[this.name] ];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };

        //获取表单的所有数据
        function getFormData()
        {
            var formData = $("#otaConfigForm").serializeObject();
            formData.cancel_rules = cancelRules.join(',');
            return formData;
        }
        //提交表单
        form.on('submit',function () {
            if($('input[name=ota_images]').val()==''){layer.msg('请至少上传一张主图！');return false;}
            if(!checkCancelRules()){return false;}
            if(!checkSaleType()){return false;}
            var formData = getFormData();
            var loading = layer.load(2);
            $.post('{:url("admin/product/update_ota_config")}',formData,function (res) {
                layer.close(loading);
                layer.msg(res.msg);
                if(res.code > 0){
                    setTimeout(function () {
                        var index = parent.layer.getFrameIndex(window.name);
                        parent.layer.close(index)
                    },1000)
                }
            },'json')
            return false;

        })

        //初始化图片
        function initOTAImage(){
            var ota_images = "{$ota_config.ota_images | default=''}";
            if(ota_images!=''){
                var ota_images_arr = ota_images.split(',');
                console.log(ota_images_arr);
                $.each(ota_images_arr,function (i,v) {
                    $('#proImageList').append('<span class="uploadimgbox"><img class="layui-upload-img" src="' + v + '"><i class="layui-icon">&#x1006;</i></span>');
                })
                $("input[name=ota_images]").val(ota_images);
            }
        }

        $(document).ready(function () {
            initOTAImage();
            //初始化取消政策
            renderCancelRuleHtml(cancelRules);
        })

        //重新渲染图片数据
        function renderImagesValue(obj,input_name)
        {
            var ota_images = [];
            $(obj).find("img").each(function(){
                ota_images.push($(this).attr("src"));
            });

            ota_images = ota_images.length < 1 ? '' : ota_images.join(',');
            $("input[name="+ input_name + "]").val(ota_images);
        }

        $('.showSaleType').on('mouseover', function(){
            var that = this;
            layer.tips('只想提示地精准些', that); //在元素的事件回调体中，follow直接赋予this即可
        });

        $('.otaTicketConfig').click(function () {
            var id = $('input[name=product_id]').val();
            var url = "/admin/product/ota_ticket_config?product_id="+id;
            layer.open({
                type:2,
                title:'门票配置',
                area:['100%','100%'],
                content:url,
                end:function () {

                }
            })
            return false;
        })
    });
</script>
</html>